using UnityEngine;
using QFramework;
using System;
using QAssetBundle;

namespace ProjectSurviver
{
	public partial class Enemy : ViewController, IEnemy
	{
		public float MovementSpeed = 2.0f;

		public float HP = 3;

		public Color DissolveColor = Color.yellow;

		private bool mIgnoreHurt = false;

		public bool TreasureChestEnemy = false;

        void Start()
        {
            EnemyGenerator.EnemyCount.Value++;
        }

        void FixedUpdate()
        {
			if(!mIgnoreHurt)
			{
				// 判断 Player.Default 是否存在场景
				if(Player.Default)
				{
					var direction = (Player.Default.transform.position- transform.position).normalized;
					SelfRigidbody2D.velocity = direction * MovementSpeed;
				}
				else
				{
					SelfRigidbody2D.velocity = Vector2.zero;
				}
			}
        }

        void Update()
        {
			if(HP <= 0)
			{
				// TODO：经验值的掉落
				Global.GeneratePowerUp(gameObject, TreasureChestEnemy);
				FxController.Play(Sprite, DissolveColor);
				AudioKit.PlaySound(Sfx.ENEMYDIE);
				//删除自己
				this.DestroyGameObjGracefully();
			}
        }

        void OnDestroy()
        {
            EnemyGenerator.EnemyCount.Value--;
        }

        public void Hurt(float value, bool force = false, bool critical = false)
        {
			if(mIgnoreHurt && !force) return;
			mIgnoreHurt = true;
			SelfRigidbody2D.velocity = Vector2.zero;
			//播放文本
			FloatingTextController.Play(transform.position, value.ToString("0"), critical);
            Sprite.color = Color.red;
			AudioKit.PlaySound(Sfx.HIT);
			//下一帧NextFrame变回白色 Delay延时
			ActionKit.Delay(0.2f, ()=>
			{
				//敌人掉血
				HP-= value;
				Sprite.color = Color.white;
				mIgnoreHurt = false;
			}).Start(this);
        }

        public void SetHPScale(float hPScale)
        {
            HP *= hPScale;
        }

        public void SetSpeedScale(float speedScale)
        {
            MovementSpeed *= speedScale;
        }
    }
}
